package cn.ichiva.web.component;

import cn.ichiva.web.common.Bus;
import cn.ichiva.web.common.Topic;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;

import java.net.URL;
import java.util.LinkedList;
import java.util.ResourceBundle;

public class AddressBar implements Initializable {

    @FXML
    TextField addressText;

    LinkedList<String> urlList = new LinkedList<>();

    @Override
    public void initialize(URL location, ResourceBundle resources) {
        Bus.subscribe(Topic.ChangeUrl,url -> {
            addressText.setText(url);
            if(urlList.size() == 0){
                urlList.addLast(url);
            }else {
                if(!urlList.getLast().equals(url)){
                    urlList.addLast(url);
                }
            }
        });

        Bus.subscribe(Topic.loadUrl,url -> {
           if(!urlList.getLast().equals(url)){
               urlList.addLast(url);
               addressText.setText(url);
           }
        });

        addressText.setOnKeyReleased(e -> {
            if(e.getCode() == KeyCode.ENTER){
                Bus.publish(Topic.TurnTo, addressText.getText());
            }
        });
    }

    public void backOff(){
        urlList.removeLast();
        String last = urlList.getLast();
        Bus.publish(Topic.TurnTo, last);
    }


    public void refresh(){
        Bus.publish(Topic.Refresh,null);
    }

    public void toUrl(){
       Bus.publish(Topic.TurnTo, addressText.getText());
    }

    public void favorite(){
        Bus.publish(Topic.Start, addressText.getText());
    }
}
